<template>
    <div>
        <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
            <!-- <el-breadcrumb-item :to="{ path: '/ManageHome' }">首页</el-breadcrumb-item> -->
            <el-breadcrumb-item>聊天应用</el-breadcrumb-item>
            <el-breadcrumb-item>聊天助手</el-breadcrumb-item>
        </el-breadcrumb>
        <div style="height: 90vh;">
            <div style="display: flex; margin-left: 20px; margin-bottom: 20px; justify-content: space-between;;">
                <div>
                    <img src="@/assets/image/aihelper.png" alt="" width="20px">
                    <span style="margin-left: 5px;">AI小助手</span>
                </div>
                <div style="padding-right: 20px;">
                    <el-select v-model="chosedModelId" placeholder="请选择模型" size="small" style="width: 120px;">
                        <el-option v-for="item in allModel" :key="item.id" :label="item.model" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-select v-model="value" placeholder="请选择应用" size="small"
                        style="margin-left: 20px; margin-right: 20px; width: 120px;">
                        <el-option v-for="item in allApp" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-button type="primary"><i class="el-icon-chat-line-round el-icon--right"></i>开启新对话</el-button>
                </div>
            </div>
            <chatV2 style="height: 85%;" :chatData="messages" @send-message="handleUserMessage"></chatV2>
        </div>
    </div>

</template>

<script>
import chat from '@/components/chat.vue';
import chatV2 from '@/components/chatV2.vue';
import request from '@/utils/request'
import { baseURL } from '@/utils/request'
import { fetchEventSource } from '@microsoft/fetch-event-source';
export default {
    components: {
        chat,
        chatV2
    },
    data() {
        return {
            chosedModelId: null,
            choseModelName: null,
            conversationId: "12232131",
            allModel: [
            ],
            chosedAppId: null,
            choseAppName: null,
            allApp: [{
                id: 1,
                name: "客服",
            },
            {
                id: 3,
                name: "企业文化",
            },
            {
                id: 3,
                name: "开发知识",
            }
            ],
            messages: [{
                content: '你好请问有什么可以帮助你',
                isUser: false,
                timeStamp: '2023-07-20T09:00:00'
            }]
        }
    },
    created() {
        this.init();

    },
    methods: {
        async init() {
            request.get("/model/all").then(res => {
                if (res.code === "1") {
                    this.allModel = res.data;
                    this.chosedModelId = this.allModel[0].id;
                } else {
                    this.allModel = [];
                    this.$message({
                        type: 'error',
                        message: res.msg
                    })
                }
            }).catch(err => {
                this.allModel = [];
                this.$message({
                    type: 'error',
                    message: res.msg
                })
            })
        },

        async handleUserMessage(userMessage) {
            // 添加用户消息
            this.messages = [...this.messages, userMessage]

            // 模拟AI回复
            const aiResponse = {
                content: '正在思考...',
                role: 'ai',
                timestamp: new Date().getTime()
            }

            this.messages = [...this.messages, aiResponse]

            // 这里实际应该调用API获取回复
            const realResponse = await this.getAIResponse(userMessage.content)

            // // 替换临时消息
            // this.messages = this.messages.map(msg =>
            //     msg.content === '正在思考...' ? realResponse : msg
            // )
        },
        async getAIResponse(query) {
            const req = {
                modelId: this.chosedModelId,
                message: query,
                conversationId: this.conversationId
            }
            let text = "";
            var len = this.messages.length;
            console.log(req)
            fetchEventSource(baseURL + "/chat/stream", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(req),
                onmessage: (event) => {
                    console.log("event",event);
                    var message = JSON.parse(event.data).message;
                    if (message == null){
                        return;
                    }
                    text += message
                    this.messages[len-1].content = text;
                },
                onerror: (error) => {
                    console.error('EventSource failed:', error);
                },
                onopen: () => {
                    console.log('Connection to server opened.');
                },
                onclose: () => {
                    console.log('Connection to server closed.');
                }
            });
        }
    }
}
</script>

<style></style>